package elasticsearch

import (
	"bawei_2112a_shop/appconfig"
	"crypto/tls"
	"fmt"
	"github.com/elastic/go-elasticsearch"
	"log"
	"net"
	"net/http"
	"sync"
	"time"
)

var (
	EsClient *elasticsearch.Client
	err      error
	once     sync.Once
)

func InitEs() {

	once.Do(func() {
		host := appconfig.AppConf.EsConfig.Host
		port := appconfig.AppConf.EsConfig.Port
		addr := fmt.Sprintf("%s:%d", host, port)
		cfg := elasticsearch.Config{
			Addresses: []string{
				addr,
			},
			Transport: &http.Transport{
				MaxIdleConnsPerHost:   10,
				ResponseHeaderTimeout: time.Second,
				DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
				TLSClientConfig: &tls.Config{
					MaxVersion:         tls.VersionTLS11,
					InsecureSkipVerify: true,
				},
			},
		}

		EsClient, err = elasticsearch.NewClient(cfg)
		if err != nil {
			log.Fatalf("es 连接失败：", err)
		}
		fmt.Println("es 连接成功")
	})
}
